<template>
  <div class="enter_submit">
    <div class="confirmInfo_title">报名缴费</div>

    <cost-list
      :calc-entry="calcEntryData"
      :entry-type="currentUserType"
      :is-use-shadow="true"
      :game-info="gameInfo"
      :game-free="gamefree"
      @onEntryEdit="onPrevStep"
      @onReGetCharges="reGetCalcEntryOrder"
    />

    <div v-if="!calcEntryData.charges && !calcEntryData.summary" v-loading="calcEntryLoading" class="no_entry">
      信息获取失败 <el-button type="text" @click="reGetCalcEntryOrder">点击重试</el-button>
    </div>

    <!-- 底部功能按钮 -->
    <el-row class="control_row">
      <el-col :span="24" align="center">
        <el-button :loading="modalPayLoding" @click="onPrevStep" v-if="!this.$route.query.insurance" >上一步</el-button>
        <el-button @click="clickPayInsurance()" :loading="modalPayLoding" v-if="!insurancecode && gamefree">缴纳保险费</el-button>
        <el-button v-if="gameInfo.setting && !isFreeGame" type="warning" :disabled="payBtnDisable || !hasPayWayInCalcEntry" :loading="modalPayLoding" @click="clickPay()">去支付</el-button>
        <el-button v-if="gameInfo.setting && isFreeGame" :loading="modalPayLoding" type="primary" @click="clickComplate()">完成</el-button>
        <el-button type="primary" @click="clickWorld()" :loading="entryWorld">下载报名明细</el-button>
      </el-col>
      <el-col v-if="!insurancecode && gamefree" :span="24" align="center" style="margin-top: 10px;">
        <el-checkbox v-model="radio">
           我已阅读并同意
        </el-checkbox>
        <span  @click="openchangse" class="insurance">
            《保险协议》
        </span>
      </el-col>
    </el-row>
    <!-- 选择支付方式弹框 -->
    <el-dialog class="gl_dialog_TitleLine" title="选择支付方式"   :visible.sync="dialogVisibleForPay" :close-on-click-modal="false" width="650px">
      <div v-loading="modalPayLoding" class="pay_type_list">
        <div class="pay_type_item pay_type_offline gl_clear" @click="clickPayOffline()">线下支付</div>
        <div class="pay_type_item pay_type_online gl_clear" @click="clickPayOnline('no')">线上支付</div>
      </div>
    </el-dialog>
    <!-- 选择支付方式弹框 -->
    <el-dialog class="gl_dialog_TitleLine" title="选择支付方式" :visible.sync="dialogVisibleForPayInsurance" :close-on-click-modal="false" width="650px">
      <div v-loading="modalPayLoding" class="pay_type_list">
        <!-- <div class="pay_type_item pay_type_offline gl_clear" @click="clickPayOffline('Insurance')">线下支付</div> -->
        <div class="pay_type_item pay_type_online gl_clear" @click="clickPayOnline('Insurance')">线上支付</div>
      </div>
    </el-dialog>
    <form id="form" ref="form" :target="inopenform?'_blank':''" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>

    <el-dialog
      class="gl_dialog_TitleLine"
      title="线下收款账户信息"
      width="640px"
      :visible.sync="offlineDialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <offline-pay-info :offline-data="offlineData" />
      <div slot="footer" class="dialog-footer">
        <el-button type="mini" @click="clickWorld()" :loading="entryWorld">下载报名明细</el-button>
        <el-button size="mini" type="primary" @click="jumpToOrderCenter">前往订单中心</el-button>
      </div>
    </el-dialog>
    <insurance ref="insurance" />
  </div>
</template>

<script>
import CostList from '@/components/CostList';
import OfflinePayInfo from '@/components/OfflinePayInfo';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import insurance from './insurance';
import {
  api_GET_EventsManagementCompetitionSettingWithCompetitionIdCompetitionId,
  api_POST_EventsManagementEntryOrdersubmitFreeOtherOrder,
  api_POST_EventsManagementEntrysubmitFreeInsuranceOrder,
  api_POST_EventsManagementEntryOrderCalculateEntryOrder, // EntryOrder 计算费用
  api_POST_EventsManagementEntryOrderSubmitOrder,
  api_POST_EventsManagementEntryOrderAllowEntry // 确认是否有未支付的订单
} from '@/extend/api/gameswaggerApi/app';

import {
  // api_GET_TradeOrderDetails, // 根据订单号获取订单详情
  api_GET_TradePersonalOrderCollectionCode, // 获取线下支付订单的收款码信息
  api_GET_TradePayOrderParameter // 获取支付订单的参数
} from '@/extend/api/swaggerApi/app';

import {
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';

export default {
  components: {
    CostList,
    OfflinePayInfo,
    insurance
  },
  props: {
    currentUserType: {
      type: String,
      default: ''
    },
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    isShow: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      orderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      dialogVisibleForPay: false,
      dialogVisibleForPayInsurance: false,
      orderNo: '', // 订单编号
      isOnlinePayment: true, // 是否是线上支付
      calcEntryData: {},
      payBtnDisable: true,
      calcEntryLoading: true,
      modalPayLoding: false,
      offlineDialogVisible: false,
      entryWorld: false,
      offlineData: {},
      gamefree: false,
      url: '',
      insurancecode: false,
      radio: false,
      inopenform: false,
    };
  },
  computed: {
    isFreeGame() {
      return this.gameInfo.setting.isFree;
    },
    hasPayWayInCalcEntry () {
      const _setOnline = this.calcEntryData.isSetOnline; // 设置了线上支付
      const _setOffline = this.calcEntryData.isSetOffline; // 设置了线下支付
      return _setOnline || _setOffline;
    }
  },
  watch: {
    isShow: {
      immediate: true,
      handler(val) {
        if (val) {
          this.calcEntryLoading = true;
          this.getCalcEntryOrder();
        }
      }
    }
  },
  methods: {
    // 点击上一步
    onPrevStep() {
      this.$emit('onPrevStep');
    },
    // 重新获取信息
    reGetCalcEntryOrder() {
      this.getCalcEntryOrder();
    },
    // 校验赛事是否收费，选择是否计算费用
    getCalcEntryOrder() {
      console.log(this.$route.fullPath);
      this.url = this.$route.fullPath;
      if( this.$route.query.insurance) {
        this.currentUserType = 'Delegation'
        this.requiredIdData.delegationId = this.$route.query.delegationId
      }
      const _vo = {
        competitionId: this.$route.query.id?this.$route.query.id: this.gameInfo.id
      };
      if (this.currentUserType === 'Personal') {
        _vo.registerId = this.$route.query.registerId?this.$route.query.registerId:this.requiredIdData.registerId;
      }
      if (this.currentUserType === 'Delegation') {
        _vo.delegationId = this.$route.query.delegationId?this.$route.query.delegationId:this.requiredIdData.delegationId

      }
      this.calcEntryOrderApi(_vo);
    },
    // 计算订单费用API
    calcEntryOrderApi (vo) {
      this.payBtnDisable = true;
      api_POST_EventsManagementEntryOrderAllowEntry(vo).then(
          res => {
            if(res.insuranceOrderInfo) {
              if(res.insuranceOrderInfo.orderStatusCode === 'TRADE_FINISHED') {
                this.insurancecode = true;
              }
              if(res.insuranceOrderInfo.orderStatusCode === 'WAIT_BUYER_PAY') {
                this.insurancecodeId = res.insuranceOrderInfo.orderNo ;
              } else {
                this.insurancecodeId = null ;
              }

            } else {
              this.insurancecode = false;
            }
          }
        )
        .catch(
          error => {
            this.$message({
              message: `费用获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
      api_GET_EventsManagementCompetitionSettingWithCompetitionIdCompetitionId(vo.competitionId).then(res => {
        this.gamefree = res.publishingIsFree;
      })
      api_POST_EventsManagementEntryOrderCalculateEntryOrder(vo)
        .then(
          res => {
            this.payBtnDisable = false;
            this.calcEntryLoading = false;
            this.calcEntryData = res;
          }
        )
        .catch(
          error => {
            this.calcEntryData = {}; // 清空数据
            this.calcEntryLoading = false;
            this.$message({
              message: `费用获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    clickWorld() {
      var that = this;
      this.entryWorld = true;
      const tempUrl = `/api/app/events-management/report`;
      const fileName = '报名明细' + '.pdf';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: 'EntryByDelegation',Format: 'PDF', CompetitionId: this.gameInfo.id,DelegationId: this.requiredIdData.delegationId }).then(res => {
        that.entryWorld = false;
      }).catch(error => {
        that.entryWorld = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 点击支付按钮
    clickPayInsurance() {
      this.inopenform = true;
      if(this.radio) {
        this.judgeIsShowDialogVisibleForPay('Insurance');
      } else {
        this.$message({
          message: `请阅读并同意《保险协议》`,
          type: 'warning',
          showClose: true
        });
      }

    },
    clickPay () {
      // if(!this.insurancecode && this.gamefree ) {
      //   this.$message({
      //     message: `先支付保险费！`,
      //     type: 'warning',
      //     showClose: true
      //   });
      //   return;
      // }
      this.inopenform = false;
      const _checkResult = this.checkFootCover();
      if (_checkResult) {
        this.judgeIsShowDialogVisibleForPay();
      } else {
        this.$message({
          message: `脚码信息不完整，请核实脚码信息！`,
          type: 'warning',
          showClose: true
        });
      }
    },
    // 判断是否显示支付方式选择弹窗
    judgeIsShowDialogVisibleForPay (row) {

      // 请注意代码顺序不可调整
      const _setOnline = row === 'Insurance'? true:this.calcEntryData.isSetOnline; // 设置了线上支付
      const _setOffline = row === 'Insurance'? false: this.calcEntryData.isSetOffline; // 设置了线下支付

      // 当同时设置了线上与线下支付时，弹窗让用户选择支付方式
      if (_setOnline && _setOffline && row !== 'Insurance') {
        this.dialogVisibleForPay = true;
        return;
      }
      if (_setOnline && _setOffline && row === 'Insurance') {
        this.dialogVisibleForPayInsurance = true;
        return;
      }

      // 仅设置了线上支付
      if (_setOnline) {
        this.clickPayOnline(row);
        return;
      }
      // 仅设置了线下支付
      if (_setOffline) {
        this.clickPayOffline(row);
        return;
      }
    },
    // 校验脚码信息是否完整
    checkFootCover () {
      const charges = this.calcEntryData.charges;
      if (charges.length) {
        const _footData = charges.find(item => item.code === 'Foot');
        if (_footData) {
          for (let i = 0; i < _footData.items.length; i++) {
            const item = _footData.items[i];
            if (item.needFootCover && !item.footSize) {
              return false;
            }
          }
        }
      }
      return true;
    },
    // 点击完成
    clickComplate () {
      const _checkResult = this.checkFootCover();
      if (_checkResult) {
        this.isOnlinePayment = true;
        this.submitOrder();
      } else {
        this.$message({
          message: `脚码信息不完整，请核实脚码信息！`,
          type: 'warning',
          showClose: true
        });
      }
    },
    // 线上支付
    clickPayOnline (row) {
      this.isOnlinePayment = true; // 是否是线上订单
      this.submitOrder(row);
    },
    // 线下支付
    clickPayOffline (row) {
      this.isOnlinePayment = false; // 是否是线上订单
      this.submitOrder(row);
    },
    // 提交订单
    submitOrder(row) {
      this.modalPayLoding = true;
      const _vo = {
        competitionId: this.gameInfo.id,
        isOnlinePayment: this.isOnlinePayment
      };
      if( this.$route.query.insurance) {
        this.currentUserType = 'Delegation'
      }
      if (this.currentUserType === 'Personal') {
        _vo.registerId = this.requiredIdData.registerId;
      }
      if (this.currentUserType === 'Delegation') {
        _vo.delegationId = this.$route.query.delegationId?this.$route.query.delegationId: this.requiredIdData.delegationId;
      }
      if( row === 'Insurance' && this.gamefree) {
        if(this.insurancecodeId) {
           this.payment(this.insurancecodeId, 'Insurance');
           this.modalPayLoding = false;
        } else {
          api_POST_EventsManagementEntrysubmitFreeInsuranceOrder(_vo)
            .then(
              res => {
                this.orderNo = res.orderNo;
                    // 如果是线上支付
                  this.payment(res.orderNo, 'Insurance');
                  this.modalPayLoding = false;
              }
            )
            .catch(
              error => {
                this.dialogVisibleForPay = false;
                this.$message({
                  message: `订单创建失败！${error.error.message}`,
                  type: 'error',
                  showClose: true
                });
                console.log(error);
                this.modalPayLoding = false;
              }
            );
        }
      } else {
        if(!this.gamefree) {
          api_POST_EventsManagementEntryOrderSubmitOrder(_vo)
        .then(
          res => {
            this.orderNo = res.orderNo;

            if (this.isFreeGame) {
              // 免费赛事跳转至报项中心
              this.$router.push({
                // path: '/myCenter/signUp/gameSignUp'
                path: '/myCenter/signUp'
              });
            } else {
              if (this.isOnlinePayment) {
                // 如果是线上支付
                this.payment(res.orderNo,'no');
              } else {
                // 线下支付，展示获取订单信息，展示收款账户信息
                this.getOrderDetails(res.orderNo);
              }
            }
          }
        )
        } else {
          api_POST_EventsManagementEntryOrdersubmitFreeOtherOrder(_vo)
        .then(
          res => {
            this.orderNo = res.orderNo;

            if (this.isFreeGame) {
              // 免费赛事跳转至报项中心
              this.$router.push({
                // path: '/myCenter/signUp/gameSignUp'
                path: '/myCenter/signUp'
              });
            } else {
              if (this.isOnlinePayment) {
                // 如果是线上支付
                this.payment(res.orderNo,'no');
              } else {
                // 线下支付，展示获取订单信息，展示收款账户信息
                this.getOrderDetails(res.orderNo);
              }
            }
          }
        )
        .catch(
          error => {
            this.modalPayLoding = false;
            this.$message({
              message: `订单详情获取失败！${error.error.message}`,
              type: 'error',
              showClose: true
            });
            console.log('getOrderDetails -> error', error);
          }
        );
        }
      }
    },
    openchangse() {
      this.$refs.insurance.dialogVisible = true;
    },
    // 去支付
    payment(orderNo, Insurance) {
      if (orderNo) {
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        let _orderUrl = ''
        console.log("🚀 ~ payment ~ _orderUrl:ssssssssssssssss", _orderUrl)
        if(Insurance === 'Insurance' && !this.$route.query.insurance) {
          this.$router.push({
            query: {
              insurance: true,
              delegationId: this.requiredIdData.delegationId,
              id:this.gameInfo.id
             }
          });
        }
        // if(Insurance === 'Insurance') {
        //   if(this.$route.query.insurance) {
        //     _orderUrl = `#${this.url}`;
        //   } else {
        //     _orderUrl = `#${this.url}&insurance=true&delegationId=${this.requiredIdData.delegationId}&registerId=${this.requiredIdData.registerId}`;
        //   }

        // } else {
        //    _orderUrl = '#/myCenter/order/main';
        // }
        _orderUrl = '#/myCenter/order/main';
        const url = _origin + _pathname + _orderUrl;
        this.orderParameterQO.OrderNo = orderNo;
        this.orderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(this.orderParameterQO)
          .then(res => {
            this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
            this.$refs.form.submit();
            if(this.inopenform) {
              window.location.reload()
            }
          })
          .catch(
          error => {
            this.$message({
              message: `${(!this.insurancecode && this.gamefree)?'保险费已支付，请支付报名费':error.error.message}`,
              type: 'error',
              showClose: true
            });
            console.log('getOrderDetails -> error', error);
          }
        );
      }
    },
    // 获取订单详情，用于线下支付展示收款账户信息
    getOrderDetails (orderNo) {
      api_GET_TradePersonalOrderCollectionCode({ orderNo: orderNo })
        .then(
          res => {
            console.log('getOrderDetails -> res', res);
            res._orderNo = orderNo;
            this.offlineData = res;
            this.offlineDialogVisible = true;
          }
        )
        .catch(
          error => {
            this.$message({
              message: `订单详情获取失败！${error.error.message}`,
              type: 'error',
              showClose: true
            });
            console.log('getOrderDetails -> error', error);
          }
        );
    },
    // 跳转到订单中心
    jumpToOrderCenter () {
      // 线下支付,直接去订单中心
      this.$router.push({
        path: '/myCenter/order/main?out_trade_no=' + this.orderNo
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.enter_submit {
  position: relative;
}
.confirmInfo_list {
  display: flex;
  flex-wrap: wrap;
  margin-right: -8px;
}
.event_table_tr {
  padding: 6px 0;
  line-height: 23px;
  border-bottom: 1px solid #dfe6ec;
}
.event_table_tr:last-child {
  border-bottom: none;
}

.pay_title {
  margin-bottom: 20px;
}
.pay_item {
  color: #606266;
  padding-top: 2px;
  font-size: 14px;
  line-height: 22px;
}
.pay_total {
  padding-top: 10px;
}

.pay_type_list {
  display: flex;
  justify-content: space-around;
}
.pay_type_item {
  width: 260px;
  height: 84px;
  padding: 0 50px;
  text-align: right;
  color: #fff;
  font-size: 24px;
  line-height: 84px;
  cursor: pointer;
}
.pay_type_online {
  background-image: url('../../../../assets/images/pay/online.png');
  background-repeat: no-repeat;
}
.pay_type_offline {
  background-image: url('../../../../assets/images/pay/offline.png');
  background-repeat: no-repeat;
}

.no_entry {
  position: relative;
  color: #909399;
  font-size: 14px;
  padding: 60px 0;
  text-align: center;
}
.insurance {
  font-size: 15px;
  color: #1890FF;
  text-decoration: underline;
  cursor: pointer;
}
</style>
